
const gameSound = {

    tags: 'ambient-eyes,ambient-4,ambient-fright,ambient-1,ambient-3,ambient-2,cutscene,death,death-double,eating-dot-double,eating-dot-1,eating-dot-2,eating-ghost,extra-life,fruit,start-music,start-music-double'.split(','),

    channels: {},

    activeSound: '',

    activeChannel: undefined,

    stopAmbientSound: undefined,

    playPromise: undefined,

    CE: function (name) {
        return document.createElement(name);
    },

    getAmbientTrack: function (name) {

        let _loc2_;

        switch (name) {
            case "ambient-1":
                _loc2_ = 381;
                break;
            case "ambient-2":
                _loc2_ = 327;
                break;
            case "ambient-3":
                _loc2_ = 298;
                break;
            case "ambient-4":
                _loc2_ = 270;
                break;
            case "ambient-fright":
                _loc2_ = 529;
                break;
            case "ambient-eyes":
                _loc2_ = 264;
                break;
            case "cutScene":
                _loc2_ = 5312;
                break;
        }
        return _loc2_;
    },

    init: function () {
        let audio, source;
        for (let item of this.tags) {
            audio = this.CE('audio');
            source = this.CE('source');
            source.type = 'audio/mpeg';
            source.src = 'pacman/sound/' + item + '.mp3';
            audio.setAttribute('name', item);
            this.channels[item] = audio;
            audio.appendChild(source);
            document.body.appendChild(audio);
        }
    },

    silence: function () {
        let active = this.activeChannel;
        if (active) {
            this.activeChannel = undefined;
            if (this.playPromise !== undefined) {
                this.playPromise.then(_ => {
                    active.pause();
                    this.playPromise = undefined;
                })
            }
        }
    },

    stopSound: function () {
        this.silence();
        this.activeSound = '';
        window.clearInterval(this.stopAmbientSound);
    },

    playTrack: function (name) {
        if (name !== this.activeSound) {
            let audio = this.activeChannel = this.channels[name];
            audio.currentTime = 0;
            this.playPromise = audio.play();
        }
    },

    playAmbientTrack: function (name) {
        if (name !== this.activeSound) {
            let loc = this.getAmbientTrack(name);
            let audio = this.channels[name];
            this.activeSound = name;
            window.clearInterval(this.stopAmbientSound);
            this.stopAmbientSound = setInterval(() => {
                audio.currentTime = 0;
            }, loc - 30);
            this.playPromise = audio.play();
        }
    }
}

gameSound.init();
